from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from app.api import deps
from app.schemas import role
from app.database.models.base import Role, Permission, User

router = APIRouter()

@router.get("/permissions", response_model=List[role.Permission])
def list_permissions(
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取所有权限列表"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    return db.query(Permission).all()

@router.post("/permissions", response_model=role.Permission)
def create_permission(
    *,
    db: Session = Depends(deps.get_db),
    permission_in: role.PermissionCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """创建新权限"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    # 检查权限代码是否已存在
    if db.query(Permission).filter(Permission.code == permission_in.code).first():
        raise HTTPException(
            status_code=400,
            detail=f"Permission code {permission_in.code} already exists"
        )
    
    permission = Permission(**permission_in.dict())
    db.add(permission)
    db.commit()
    db.refresh(permission)
    return permission

@router.get("/roles", response_model=List[role.Role])
def list_roles(
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取所有角色列表"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    return db.query(Role).all()

@router.post("/roles", response_model=role.Role)
def create_role(
    *,
    db: Session = Depends(deps.get_db),
    role_in: role.RoleCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """创建新角色"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    # 检查角色名是否已存在
    if db.query(Role).filter(Role.name == role_in.name).first():
        raise HTTPException(
            status_code=400,
            detail=f"Role {role_in.name} already exists"
        )
    
    # 获取权限
    permissions = db.query(Permission).filter(
        Permission.id.in_(role_in.permission_ids)
    ).all()
    if len(permissions) != len(role_in.permission_ids):
        raise HTTPException(status_code=400, detail="Invalid permission ids")
    
    # 创建角色
    db_role = Role(
        name=role_in.name,
        description=role_in.description,
        permissions=permissions
    )
    db.add(db_role)
    db.commit()
    db.refresh(db_role)
    return db_role

@router.get("/roles/{role_id}", response_model=role.Role)
def get_role(
    *,
    db: Session = Depends(deps.get_db),
    role_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取特定角色信息"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    db_role = db.query(Role).filter(Role.id == role_id).first()
    if not db_role:
        raise HTTPException(status_code=404, detail="Role not found")
    return db_role

@router.put("/roles/{role_id}", response_model=role.Role)
def update_role(
    *,
    db: Session = Depends(deps.get_db),
    role_id: int,
    role_in: role.RoleUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新角色信息"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    db_role = db.query(Role).filter(Role.id == role_id).first()
    if not db_role:
        raise HTTPException(status_code=404, detail="Role not found")
    
    # 更新基本信息
    if role_in.name is not None:
        db_role.name = role_in.name
    if role_in.description is not None:
        db_role.description = role_in.description
    
    # 更新权限
    if role_in.permission_ids is not None:
        permissions = db.query(Permission).filter(
            Permission.id.in_(role_in.permission_ids)
        ).all()
        if len(permissions) != len(role_in.permission_ids):
            raise HTTPException(status_code=400, detail="Invalid permission ids")
        db_role.permissions = permissions
    
    db.add(db_role)
    db.commit()
    db.refresh(db_role)
    return db_role

@router.delete("/roles/{role_id}")
def delete_role(
    *,
    db: Session = Depends(deps.get_db),
    role_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """删除角色"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    db_role = db.query(Role).filter(Role.id == role_id).first()
    if not db_role:
        raise HTTPException(status_code=404, detail="Role not found")
    
    # 检查是否有用户正在使用该角色
    if db.query(User).filter(User.role == db_role.name).first():
        raise HTTPException(
            status_code=400,
            detail="Cannot delete role that is being used by users"
        )
    
    db.delete(db_role)
    db.commit()
    return {"ok": True} 